package com.xiaozhengkeji.springboot.frame.easy.api;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.xiaozhengkeji.springboot.frame.easy.Bean.QueryInfo;
import com.xiaozhengkeji.springboot.frame.easy.Bean.ResponseBean;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysGoods;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysPayOrder;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysUser;
import com.xiaozhengkeji.springboot.frame.easy.security.JwtTokenUtil;
import com.xiaozhengkeji.springboot.frame.easy.service.SysGoodsService;
import com.xiaozhengkeji.springboot.frame.easy.service.SysPayOrderService;
import com.xiaozhengkeji.springboot.frame.easy.service.SysUserService;
import com.xiaozhengkeji.springboot.frame.easy.utils.DaysUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/pay")
public class PayApi {
    @Autowired
    private SysGoodsService sysGoodsService;
    @Autowired
    private SysPayOrderService sysPayOrderService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private SysUserService sysUserService;

    /*查询全部订单*/
    @GetMapping("/all")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean allPay(@RequestHeader String Token,
                               QueryInfo queryInfo) {

        String username = jwtTokenUtil.getUsernameFromToken(Token.substring("Bearer ".length()));
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser = sysUserService.queryAll(sysUser).get(0);
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize(); //页码

        if (sysUser.getUserRole().equalsIgnoreCase("ROLE_def")) {
            SysPayOrder sysPayOrder = new SysPayOrder();
            sysPayOrder.setUserUuid(sysUser.getUuid());
            List<SysPayOrder> sysPayOrders = sysPayOrderService.queryAll(sysPayOrder);
            return new ResponseBean(sysPayOrders.size(), "ok", sysPayOrders.subList(pageStart, queryInfo.getPageSize()));
        }

        List<SysPayOrder> sysPayOrders = sysPayOrderService.queryAll(new SysPayOrder());
        return new ResponseBean(sysPayOrders.size(), "ok", sysPayOrderService.queryAllByLimit(pageStart, queryInfo.getPageSize()));
    }

    /*创建新订单*/
    @GetMapping("/add")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean addPay(@RequestHeader String Token,
                               @RequestParam("id") Integer id) {

        SysGoods sysGoods = sysGoodsService.queryById(id);
        if (sysGoods == null) {
            return new ResponseBean(404, "无法创建商品ID为: " + String.valueOf(id) + "的订单", null);
        }
        String username = jwtTokenUtil.getUsernameFromToken(Token.substring("Bearer ".length()));
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser = sysUserService.queryAll(sysUser).get(0);
        Date day = new Date();
        SysPayOrder sysPayOrder = new SysPayOrder();
        sysPayOrder.setOrderId(DaysUtil.DateToString(day));
        sysPayOrder.setGid(id);
        sysPayOrder.setUserUuid(sysUser.getUuid());
        sysPayOrder.setFoundDate(day);
        sysPayOrder.setPayState("订单等待创建");
        try {
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(sysGoods.getTitle(), sysPayOrder.getOrderId(), sysGoods.getRmb());
            sysPayOrder.setPayState("订单等待支付");
            sysPayOrder.setPayUrl(response.qrCode);
            sysPayOrderService.insert(sysPayOrder);
            return new ResponseBean(sysPayOrder.getId(), "ok", response.qrCode);
        } catch (Exception e) {
            return new ResponseBean(404, "无法创建商品ID为: " + String.valueOf(id) + "的订单", null);
        }

    }

    /*查询订单*/
    @GetMapping("/payInfo")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean payInfo(@RequestParam("id") Integer id) {
        SysPayOrder sysPayOrder = sysPayOrderService.queryById(id);
        if (sysPayOrder == null) {
            return new ResponseBean(404, "数据库未查询到本订单", null);
        }
        try {
            AlipayTradeQueryResponse alipayTradeQueryResponse = Factory.Payment.Common().query(sysPayOrder.getOrderId());
            switch (alipayTradeQueryResponse.tradeStatus) {
                case "WAIT_BUYER_PAY":
                    sysPayOrder.setPayState("等待买家付款");
                    break;
                case "TRADE_CLOSED":
                    sysPayOrder.setPayState("订单无效");
                    break;
                case "TRADE_SUCCESS":
                    sysPayOrder.setPayState("交易支付成功");
                    break;
                case "TRADE_FINISHED":
                    sysPayOrder.setPayState("交易结束");
                    break;
                default:
            }

            return new ResponseBean(200, "ok", sysPayOrderService.update(sysPayOrder));
        } catch (Exception e) {
            return new ResponseBean(500, "Cloud服务出错", sysPayOrder);
        }
    }

    /*修改订单*/
    @PutMapping("/edit")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ResponseBean editPay(@RequestHeader String Token,
                                @RequestBody SysPayOrder sysPayOrder) {

        if (sysPayOrderService.update(sysPayOrder) == null) {
            return new ResponseBean(500, "修改失败", null);
        }
        return new ResponseBean(200, "修改成功", null);

    }

    /*删除订单*/
    @DeleteMapping("/delete")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ResponseBean deletePay(@RequestHeader String Token,
                                  @RequestParam("id") Integer id) {


        if (sysPayOrderService.deleteById(id)) {
            return new ResponseBean(200, "success", null);
        }
        return new ResponseBean(500, "error", null);
    }
}
